#include <vector>
using namespace std;

vector<int> spiralOrder(vector<vector<int>> &matrix) {
  vector<int> res;
  int rows = matrix.size();
  int cols = matrix[0].size();
  // 1.输出第一行
  // 2.输出最后一列
  // 3.逆序输出最后一行
  // 4.逆序输出第一列
  int row = 0;
  int col = 0;
  int start_row = 0, start_col = 0, end_row = rows - 1, end_col = cols - 1;
  // 无可处理数据
  while (start_row <= end_row && start_col <= end_col) {
    // 处理第一行
    if (end_col >= start_col && end_row >= start_row) {
      for (int col = start_col; col <= end_col; col++) {
        res.push_back(matrix[start_row][col]);
      }
      start_row++;
    }

    // 旋转 处理最后一列
    // 判断是否存在多行数据
    if (end_row >= start_row && end_col >= start_col) {
      for (int row = start_row; row <= end_row; row++) {
        res.push_back(matrix[row][end_col]);
      }
      end_col--;
    }
    // 旋转 处理最后一行
    if (end_col >= start_col && end_row >= start_row) {
      for (int col = end_col; col >= start_col; col--) {
        res.push_back(matrix[end_row][col]);
      }
      end_row--;
    }
    // 旋转 处理第一列
    if (end_col >= start_col && end_row > start_row) {
      for (int row = end_row; row >= start_row; row--) {
        res.push_back(matrix[row][start_col]);
      }
      start_col++;
    }
  }
  return res;
}